﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZenHR.AttData.Collection;
using ZenHR.AttData.DAL;

namespace ZenHR.AttData.ConfigTools
{
    public partial class frm_Main : Form
    {


        public frm_Main()
        {
            InitializeComponent();
          

        }

        private void frm_Main_Load(object sender, EventArgs e)
        {
           BindGrid("");

           BindGridAppConfig();

           BindCmb();
        }

        private void BindCmb()
        {
            try
            {
                BaseDAL _BaseDAL = new BaseDAL();
                var _table = _BaseDAL.GetALLTaskCodeList();
                cmb_task_code.DataSource = _table;
                cmb_task_code.ValueMember = "TaskCode";
                cmb_task_code.DisplayMember = "TaskCode";
            }
            catch (Exception)
            {

                throw;
            }
        }

        private void BindGrid(string p_task_code)
        {

            this.dg_cloud.DataSource = null;
            this.dg_cloud.Rows.Clear();
            this.dg_cloud.Columns.Clear();

            BaseDAL _BaseDAL = new BaseDAL();

            var _table = _BaseDAL.GetAllTaskRunTimeInfo(p_task_code);
            dg_cloud.DataSource = _table;

            dg_cloud.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;

            //添加保存按钮
            DataGridViewButtonColumn col_save_btn = new DataGridViewButtonColumn();
            col_save_btn.Name = "btn_save";
            col_save_btn.HeaderText = "";
            col_save_btn.DefaultCellStyle.NullValue = "保存";
            dg_cloud.Columns.Add(col_save_btn);

            //添加删除按钮
            DataGridViewButtonColumn col_del_btn = new DataGridViewButtonColumn();
            col_del_btn.Name = "btn_del";
            col_del_btn.HeaderText = "";
            col_del_btn.DefaultCellStyle.NullValue = "删除";
            dg_cloud.Columns.Add(col_del_btn);

            //查看当前批次数据
            DataGridViewButtonColumn col_csv_btn = new DataGridViewButtonColumn();
            col_csv_btn.Name = "btn_csv";
            col_csv_btn.HeaderText = "";
            col_csv_btn.DefaultCellStyle.NullValue = "查看";
            dg_cloud.Columns.Add(col_csv_btn);

            //删除
            DataGridViewButtonColumn col_deldata_btn = new DataGridViewButtonColumn();
            col_deldata_btn.Name = "btn_deldata";
            col_deldata_btn.HeaderText = "";
            col_deldata_btn.DefaultCellStyle.NullValue = "删除批次";
            dg_cloud.Columns.Add(col_deldata_btn);


            //手工执行
            DataGridViewButtonColumn col_run_btn = new DataGridViewButtonColumn();
            col_run_btn.Name = "btn_run";
            col_run_btn.HeaderText = "";
            col_run_btn.DefaultCellStyle.NullValue = "手工执行";
            dg_cloud.Columns.Add(col_run_btn);



            //手工执行
            DataGridViewButtonColumn col_run_btn_batch = new DataGridViewButtonColumn();
            col_run_btn_batch.Name = "btn_run_batch";
            col_run_btn_batch.HeaderText = "";
            col_run_btn_batch.DefaultCellStyle.NullValue = "手工批次";
            dg_cloud.Columns.Add(col_run_btn_batch);


            dg_cloud.Columns[0].Width = 20;
            dg_cloud.Columns[1].Width = 50;
            dg_cloud.Columns[2].Width = 50;
            dg_cloud.Columns[4].Width = 50;
            dg_cloud.Columns[5].Width = 210;
            dg_cloud.Columns[6].Width = 310;
            dg_cloud.Columns[7].Width = 48;

            dg_cloud.Columns[8].Width = 60;
            dg_cloud.Columns[9].Width = 60;
            dg_cloud.Columns[10].Width = 60;
            dg_cloud.Columns[11].Width = 60;
            dg_cloud.Columns[12].Width = 80;
            dg_cloud.Columns[13].Width = 80;
            dg_cloud.Columns[14].Width = 80;

        }

        /// <summary>
        /// 
        /// </summary>
        private void BindGridAppConfig()
        {

            this.dg_appConfig.DataSource = null;
            this.dg_appConfig.Rows.Clear();
            this.dg_appConfig.Columns.Clear();


            BaseDAL _BaseDAL = new BaseDAL();

            var _table = _BaseDAL.GetAppConfig();
            dg_appConfig.DataSource = _table;

            //添加保存按钮
            DataGridViewButtonColumn col_save_btn = new DataGridViewButtonColumn();
            col_save_btn.Name = "btn_save";
            col_save_btn.HeaderText = "保存";
            col_save_btn.DefaultCellStyle.NullValue = "保存";
            dg_appConfig.Columns.Add(col_save_btn);

            dg_appConfig.Columns[0].Width = 80;
            dg_appConfig.Columns[1].Width = 80;
            dg_appConfig.Columns[2].Width = 80;
            dg_appConfig.Columns[3].Width = 80;
            dg_appConfig.Columns[4].Width = 80;
            //dg_appConfig.Columns[5].Width = 0;

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dg_cloud_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dg_cloud.Columns[e.ColumnIndex].Name == "btn_save" && e.RowIndex >= 0)
            {
                BaseDAL _BaseDAL = new BaseDAL();

                if (_BaseDAL.SaveTaskRunTimeInfo(
                      dg_cloud.CurrentRow.Cells["taskdb"].Value.ToString(),
                      dg_cloud.CurrentRow.Cells["id"].Value.ToString(),
                      dg_cloud.CurrentRow.Cells["task_code"].Value.ToString(),
                      dg_cloud.CurrentRow.Cells["run_time"].Value.ToString(),
                      dg_cloud.CurrentRow.Cells["sql_type"].Value.ToString(),
                      dg_cloud.CurrentRow.Cells["connectionString"].Value.ToString(),
                      dg_cloud.CurrentRow.Cells["sql_str"].Value.ToString(),
                      dg_cloud.CurrentRow.Cells["last_run_time"].Value.ToString(),
                      int.Parse(dg_cloud.CurrentRow.Cells["current_index"].Value.ToString()),
                      dg_cloud.CurrentRow.Cells["mail_address"].Value.ToString()
                      ) > 0)
                {
                    MessageBox.Show("保存成功！");
                    BindGrid(cmb_task_code.Text);
                }

            }

            if (dg_cloud.Columns[e.ColumnIndex].Name == "btn_del" && e.RowIndex >= 0)
            {
                BaseDAL _BaseDAL = new BaseDAL();

                if (_BaseDAL.DelTaskRunTimeInfo(dg_cloud.CurrentRow.Cells["id"].Value.ToString())> 0)
                {
                    MessageBox.Show("删除成功！");

                    BindGrid(cmb_task_code.Text);
                }

            }

            if (dg_cloud.Columns[e.ColumnIndex].Name == "btn_csv" && e.RowIndex >= 0)
            {
                BaseDAL _BaseDAL = new BaseDAL();
                var _batchList = _BaseDAL.GetLastBatchID(dg_cloud.CurrentRow.Cells["taskdb"].Value.ToString(),dg_cloud.CurrentRow.Cells["task_code"].Value.ToString());


                var _batchID = "";
                if (_batchList.Rows.Count > 0)
                {
                    _batchID +=  _batchList.Rows[0][0].ToString() + System.Environment.NewLine;
                }

                txt_batchstr.Text = "【本地批次号列表】" + dg_cloud.CurrentRow.Cells["task_code"].Value.ToString() + " :" + System.Environment.NewLine + _batchID;

                if (txt_batchID.Text == "")
                {
                    MessageBox.Show("请先输入需要查看的批次号！（本地批次号信息请在【相关信息】中查看）");

                    return;
                }

                   
                var _table = _BaseDAL.SearchCurrentBatchTaskData(dg_cloud.CurrentRow.Cells["taskdb"].Value.ToString(),"att_data_" + dg_cloud.CurrentRow.Cells["task_code"].Value.ToString(),txt_batchID.Text);

                AnalyzeStrHelper.datatableToCSV(_table, AppDomain.CurrentDomain.BaseDirectory + @"Csv_File\" + "att_data_" + dg_cloud.CurrentRow.Cells["task_code"].Value.ToString() +".csv");

                string v_OpenFolderPath = AppDomain.CurrentDomain.BaseDirectory + @"Csv_File\";
                System.Diagnostics.Process.Start("explorer.exe", v_OpenFolderPath);

            }

            if (dg_cloud.Columns[e.ColumnIndex].Name == "btn_deldata" && e.RowIndex >= 0)
            {
                BaseDAL _BaseDAL = new BaseDAL();

                if (_BaseDAL.Delatt_data(dg_cloud.CurrentRow.Cells["taskdb"].Value.ToString(),dg_cloud.CurrentRow.Cells["task_code"].Value.ToString()) > 0)
                {
                    MessageBox.Show("删除成功！");

                    BindGrid(cmb_task_code.Text);
                }
            }

            if (dg_cloud.Columns[e.ColumnIndex].Name == "btn_run" && e.RowIndex >= 0)
            {
                //完整采集后执行一次
                TaskRun.Run(dg_cloud.CurrentRow.Cells["id"].Value.ToString());
            }

            if (dg_cloud.Columns[e.ColumnIndex].Name == "btn_run_batch" && e.RowIndex >= 0)
            {
                Process _isupdate = new Process();
                BaseDAL _BaseDAL = new BaseDAL();

                var _batchID = txt_batchID.Text;
                if (_batchID != "")
                {
                    MessageBox.Show(_batchID);
                    txt_cmd_info.Text = "ZenHR.AttData.Package.exe " + dg_cloud.CurrentRow.Cells["id"].Value.ToString() + " " + dg_cloud.CurrentRow.Cells["task_code"].Value.ToString() + " " + _batchID + " " + dg_cloud.CurrentRow.Cells["sql_type"].Value.ToString() + " " + dg_cloud.CurrentRow.Cells["mail_address"].Value.ToString();
                    //_isupdate.StartInfo.FileName = AppDomain.CurrentDomain.BaseDirectory + "\\ZenHR.AttData.Package.exe";
                    Process.Start(AppDomain.CurrentDomain.BaseDirectory + "\\ZenHR.AttData.Package.exe", dg_cloud.CurrentRow.Cells["id"].Value.ToString() + " " + dg_cloud.CurrentRow.Cells["task_code"].Value.ToString() + " " + _batchID + " " + dg_cloud.CurrentRow.Cells["sql_type"].Value.ToString() + " " + dg_cloud.CurrentRow.Cells["mail_address"].Value.ToString() + " " + dg_cloud.CurrentRow.Cells["taskdb"].Value.ToString());

                }
                else
                {
                    MessageBox.Show("请输入需要执行的BatchID！");
                }
            }


        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dg_appConfig_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dg_appConfig.Columns[e.ColumnIndex].Name == "btn_save" && e.RowIndex >= 0)
            {
                BaseDAL _BaseDAL = new BaseDAL();

                if (_BaseDAL.UpdateAppConfig(
                      dg_appConfig.CurrentRow.Cells["mail_host"].Value.ToString(),
                      dg_appConfig.CurrentRow.Cells["mail_user_name"].Value.ToString(),
                      dg_appConfig.CurrentRow.Cells["mail_pwd"].Value.ToString(),
                      dg_appConfig.CurrentRow.Cells["mail_name"].Value.ToString(),
                      dg_appConfig.CurrentRow.Cells["error_mail"].Value.ToString(),
                      dg_appConfig.CurrentRow.Cells["co_code"].Value.ToString(),
                      dg_appConfig.CurrentRow.Cells["zenhr_if"].Value.ToString(),
                      dg_appConfig.CurrentRow.Cells["zenhr_iftoken"].Value.ToString(),
                      dg_appConfig.CurrentRow.Cells["interface_id"].Value.ToString(),
                      dg_appConfig.CurrentRow.Cells["oss_token"].Value.ToString(),
                      dg_appConfig.CurrentRow.Cells["key"].Value.ToString()
                      ) > 0)
                {
                    MessageBox.Show("保存成功！");
                    BindGrid(cmb_task_code.Text);
                }

            }
        }

        private void btn_strformat_Click(object sender, EventArgs e)
        {
            
            string file_format = txt_formatStr.Text;
            int? cardno_startpoint = null, cardno_endpoint = null, year_startpoint = null, year_endpoint = null, month_startpoint = null, month_endpoint = null, day_startpoint = null, day_endpoint = null, hour_startpoint = null, hour_endpoint = null, minute_startpoint = null, minute_endpoint = null, second_startpoint = null, second_endpoint = null, location_startpoint = null, location_endpoint = null;
           
            Dictionary<int, string> allresult = AnalyzeStrHelper.AnalyzeStr(file_format);
            var queryPoint = from p in allresult where p.Value.Contains("C") select p;
            if (queryPoint.Count() > 0)
            {
                cardno_startpoint = queryPoint.First().Key;
                cardno_endpoint = queryPoint.First().Value.Length + queryPoint.First().Key - 1;
            }
            queryPoint = from p in allresult where p.Value.Contains("Y") select p;
            if (queryPoint.Count() > 0)
            {
                year_startpoint = queryPoint.First().Key;
                year_endpoint = queryPoint.First().Value.Length + queryPoint.First().Key - 1;
            }
            queryPoint = from p in allresult where p.Value.Contains("M") select p;
            if (queryPoint.Count() > 0)
            {
                month_startpoint = queryPoint.First().Key;
                month_endpoint = queryPoint.First().Value.Length + queryPoint.First().Key - 1;
            }
            queryPoint = from p in allresult where p.Value.Contains("D") select p;
            if (queryPoint.Count() > 0)
            {
                day_startpoint = queryPoint.First().Key;
                day_endpoint = queryPoint.First().Value.Length + queryPoint.First().Key - 1;
            }
            queryPoint = from p in allresult where p.Value.Contains("H") select p;
            if (queryPoint.Count() > 0)
            {
                hour_startpoint = queryPoint.First().Key;
                hour_endpoint = queryPoint.First().Value.Length + queryPoint.First().Key - 1;
            }
            queryPoint = from p in allresult where p.Value.Contains("N") select p;
            if (queryPoint.Count() > 0)
            {
                minute_startpoint = queryPoint.First().Key;
                minute_endpoint = queryPoint.First().Value.Length + queryPoint.First().Key - 1;
            }
            queryPoint = from p in allresult where p.Value.Contains("S") select p;
            if (queryPoint.Count() > 0)
            {
                second_startpoint = queryPoint.First().Key;
                second_endpoint = queryPoint.First().Value.Length + queryPoint.First().Key - 1;
            }
            queryPoint = from p in allresult where p.Value.Contains("L") select p;
            if (queryPoint.Count() > 0)
            {
                location_startpoint = queryPoint.First().Key;
                location_endpoint = queryPoint.First().Value.Length + queryPoint.First().Key - 1;
            }

            lbl_value.Text = "C 卡号   ：" + txt_strdata.Text.Substring(cardno_startpoint.Value-1, cardno_endpoint.Value + 1 - cardno_startpoint.Value) + System.Environment.NewLine;
            lbl_value.Text += "L 考勤机号：" + txt_strdata.Text.Substring(location_startpoint.Value - 1, location_endpoint.Value + 1 - location_startpoint.Value) + System.Environment.NewLine;
            lbl_value.Text += "Y 年份   ：" + txt_strdata.Text.Substring(year_startpoint.Value - 1, year_endpoint.Value + 1 - year_startpoint.Value) + System.Environment.NewLine;
            lbl_value.Text += "M 月份   ：" + txt_strdata.Text.Substring(month_startpoint.Value - 1, month_endpoint.Value + 1 - month_startpoint.Value) + System.Environment.NewLine;
            lbl_value.Text += "D 日    ：" + txt_strdata.Text.Substring(day_startpoint.Value - 1, day_endpoint.Value + 1 - day_startpoint.Value) + System.Environment.NewLine;
            lbl_value.Text += "H 小时   ：" + txt_strdata.Text.Substring(hour_startpoint.Value - 1, hour_endpoint.Value + 1 - hour_startpoint.Value) + System.Environment.NewLine;
            lbl_value.Text += "N 分    ：" + txt_strdata.Text.Substring(minute_startpoint.Value - 1, minute_endpoint.Value + 1 - minute_startpoint.Value) + System.Environment.NewLine;
            //  lbl_value.Text += "X 其他：" + txt_strdata.Text.Substring(cardno_startpoint.Value - 1, cardno_endpoint.Value - cardno_startpoint.Value) + System.Environment.NewLine;

            //lbl_value.Text += string.Format("select id,task_code,run_time,last_run_time,sql_type,connectionString,sql_str,b.error_mail,current_index from task_run_time_info as a left join app_config as b where IFNULL(datetime(last_run_time),'1990-01-01 00:00')<='{0}' and datetime('{1}')>( '{2}' || ' '|| run_time)", DateTime.Now.Date.ToString("yyyy-MM-dd 00:00:00"), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), DateTime.Now.ToString("yyyy-MM-dd"));
        }

        private void btn_reload_Click(object sender, EventArgs e)
        {
            BindGrid(cmb_task_code.Text);
        }

        private void tabPage1_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (dg_cloud.DefaultCellStyle.WrapMode == DataGridViewTriState.True)
            {
                dg_cloud.DefaultCellStyle.WrapMode = DataGridViewTriState.False;

            }
            else {

                dg_cloud.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
            }
        }

        
        /// <summary>
        /// TaskCode下拉框变更
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmb_task_code_ValueMemberChanged(object sender, EventArgs e)
        {
        
        }

        private void cmb_task_code_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindGrid(cmb_task_code.Text);
        }

        /// <summary>
        /// 点击查询本地缓存的打卡信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_search_cardInfo_Click(object sender, EventArgs e)
        {
            BaseDAL _BaseDAL = new BaseDAL();
            DataSet _ds=  _BaseDAL.SearchAttDataFromAllData(txt_emp_code_card.Text, dtp_start.Value.ToString("yyyy-MM-dd"), dtp_end.Value.ToString("yyyy-MM-dd"));

            var _all_table = GetAllDataTable(_ds);

            AnalyzeStrHelper.datatableToCSV(_all_table, AppDomain.CurrentDomain.BaseDirectory + @"Csv_File\" + "All_Data" + ".csv");

            string v_OpenFolderPath = AppDomain.CurrentDomain.BaseDirectory + @"Csv_File\";
            System.Diagnostics.Process.Start("explorer.exe", v_OpenFolderPath);
        }

        public DataTable GetAllDataTable(DataSet ds)
        {
            DataTable newDataTable = ds.Tables[0].Clone();                //创建新表 克隆以有表的架构。
            object[] objArray = new object[newDataTable.Columns.Count];   //定义与表列数相同的对象数组 存放表的一行的值。
            for (int i = 0; i < ds.Tables.Count; i++)
            {
                for (int j = 0; j < ds.Tables[i].Rows.Count; j++)
                {
                    ds.Tables[i].Rows[j].ItemArray.CopyTo(objArray, 0);    //将表的一行的值存放数组中。
                    newDataTable.Rows.Add(objArray);                       //将数组的值添加到新表中。
                }
            }
            return newDataTable;                                           //返回新表。
        }

    }
}
